package controllers

import (
	"encoding/json"
	"strconv"
	"supershare/backend/middleware"
	"supershare/backend/models"

	"github.com/beego/beego/v2/server/web"
)

// CityController 城市管理控制器
type CityController struct {
	web.Controller
}

// CityListRequest 城市列表请求参数
type CityListRequest struct {
	Page     int    `json:"page" form:"page"`
	PageSize int    `json:"pageSize" form:"pageSize"`
	Name     string `json:"name" form:"name"`
	Province string `json:"province" form:"province"`
	Status   int8   `json:"status" form:"status"`
	IsHot    int8   `json:"is_hot" form:"is_hot"`
}

// CityCreateRequest 创建城市请求参数
type CityCreateRequest struct {
	Name      string  `json:"name"`
	Code      string  `json:"code"`
	Province  string  `json:"province"`
	Latitude  float64 `json:"latitude"`
	Longitude float64 `json:"longitude"`
	IsHot     int8    `json:"is_hot"`
	SortOrder int     `json:"sort_order"`
	Status    int8    `json:"status"`
}

// CityUpdateRequest 更新城市请求参数
type CityUpdateRequest struct {
	Name      string  `json:"name"`
	Code      string  `json:"code"`
	Province  string  `json:"province"`
	Latitude  float64 `json:"latitude"`
	Longitude float64 `json:"longitude"`
	IsHot     int8    `json:"is_hot"`
	SortOrder int     `json:"sort_order"`
	Status    int8    `json:"status"`
}

// List 获取城市列表
func (c *CityController) List() {
	// 获取请求参数
	page, _ := strconv.Atoi(c.GetString("page"))
	if page <= 0 {
		page = 1
	}

	pageSize, _ := strconv.Atoi(c.GetString("pageSize"))
	if pageSize <= 0 || pageSize > 100 {
		pageSize = 10
	}

	name := c.GetString("name")
	province := c.GetString("province")
	status, _ := c.GetInt8("status", -1)
	isHot, _ := c.GetInt8("is_hot", -1)

	// 获取当前管理员信息
	admin, err := middleware.GetCurrentAdmin(c.Ctx)
	if err != nil || admin == nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "未授权访问",
		}
		c.ServeJSON()
		return
	}

	// 构建过滤条件
	filters := make(map[string]interface{})
	if name != "" {
		filters["name"] = name
	}
	if province != "" {
		filters["province"] = province
	}
	if status >= 0 {
		filters["status"] = int8(status)
	}
	if isHot >= 0 {
		filters["is_hot"] = int8(isHot)
	}

	// 查询城市列表
	cities, total, err := models.GetCityList(page, pageSize, filters)
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "获取城市列表失败",
		}
		c.ServeJSON()
		return
	}

	// 返回结果
	c.Data["json"] = map[string]interface{}{
		"success": true,
		"message": "获取城市列表成功",
		"data": map[string]interface{}{
			"list":  cities,
			"total": total,
		},
	}
	c.ServeJSON()
}

// GetAll 获取所有城市（不分页）
func (c *CityController) GetAll() {
	// 获取请求参数
	status, _ := c.GetInt8("status", 1) // 默认只获取启用的城市
	isHot, _ := c.GetInt8("is_hot", -1)

	// 构建过滤条件
	filters := make(map[string]interface{})
	if status >= 0 {
		filters["status"] = int8(status)
	}
	if isHot >= 0 {
		filters["is_hot"] = int8(isHot)
	}

	// 查询所有城市
	cities, err := models.GetAllCities(filters)
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "获取城市列表失败",
		}
		c.ServeJSON()
		return
	}

	// 返回结果
	c.Data["json"] = map[string]interface{}{
		"success": true,
		"message": "获取城市列表成功",
		"data":    cities,
	}
	c.ServeJSON()
}

// Create 创建城市
func (c *CityController) Create() {
	// 解析请求参数
	var req CityCreateRequest
	err := json.Unmarshal(c.Ctx.Input.RequestBody, &req)
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "无效的请求参数",
		}
		c.ServeJSON()
		return
	}

	// 获取当前管理员信息
	admin, err := middleware.GetCurrentAdmin(c.Ctx)
	if err != nil || admin == nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "未授权访问",
		}
		c.ServeJSON()
		return
	}

	// 创建城市
	city := &models.City{
		Name:      req.Name,
		Code:      req.Code,
		Province:  req.Province,
		Latitude:  req.Latitude,
		Longitude: req.Longitude,
		IsHot:     req.IsHot,
		SortOrder: req.SortOrder,
		Status:    req.Status,
	}

	// 设置创建者信息
	city.CreatedBy = admin.Username
	city.UpdatedBy = admin.Username
	city.BeforeInsert()
	// 保存到数据库
	id, err := models.CreateCity(city)
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "创建城市失败: " + err.Error(),
		}
		c.ServeJSON()
		return
	}

	// 返回结果
	c.Data["json"] = map[string]interface{}{
		"success": true,
		"message": "创建城市成功",
		"data": map[string]interface{}{
			"id": id,
		},
	}
	c.ServeJSON()
}

// Update 更新城市
func (c *CityController) Update() {
	// 获取城市ID
	id, _ := strconv.ParseInt(c.Ctx.Input.Param(":id"), 10, 64)
	if id <= 0 {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "无效的城市ID",
		}
		c.ServeJSON()
		return
	}

	// 解析请求参数
	var req CityUpdateRequest
	err := json.Unmarshal(c.Ctx.Input.RequestBody, &req)
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "无效的请求参数",
		}
		c.ServeJSON()
		return
	}

	// 获取当前管理员信息
	admin, err := middleware.GetCurrentAdmin(c.Ctx)
	if err != nil || admin == nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "未授权访问",
		}
		c.ServeJSON()
		return
	}

	// 获取城市信息
	city, err := models.GetCityById(id)
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "城市不存在",
		}
		c.ServeJSON()
		return
	}

	// 更新城市信息
	city.Name = req.Name
	city.Code = req.Code
	city.Province = req.Province
	city.Latitude = req.Latitude
	city.Longitude = req.Longitude
	city.IsHot = req.IsHot
	city.SortOrder = req.SortOrder
	city.Status = req.Status
	city.UpdatedBy = admin.Username
	city.BeforeUpdate()
	// 保存到数据库
	err = models.UpdateCity(city, "Name", "Code", "Province", "Latitude", "Longitude", "IsHot", "SortOrder", "Status", "UpdatedBy", "UpdatedAt")
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "更新城市失败: " + err.Error(),
		}
		c.ServeJSON()
		return
	}

	// 返回结果
	c.Data["json"] = map[string]interface{}{
		"success": true,
		"message": "更新城市成功",
	}
	c.ServeJSON()
}

// Delete 删除城市
func (c *CityController) Delete() {
	// 获取城市ID
	id, _ := strconv.ParseInt(c.Ctx.Input.Param(":id"), 10, 64)
	if id <= 0 {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "无效的城市ID",
		}
		c.ServeJSON()
		return
	}

	// 获取当前管理员信息
	admin, err := middleware.GetCurrentAdmin(c.Ctx)
	if err != nil || admin == nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "未授权访问",
		}
		c.ServeJSON()
		return
	}

	// 删除城市
	err = models.DeleteCity(id)
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "删除城市失败: " + err.Error(),
		}
		c.ServeJSON()
		return
	}

	// 返回结果
	c.Data["json"] = map[string]interface{}{
		"success": true,
		"message": "删除城市成功",
	}
	c.ServeJSON()
}
